
/**
 * Created by Administrator on 2017/11/16 0016.
 */
var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxDesignUserDocModel = function (obj) {
    YjxBaseModel.call(this,obj);
};

YjxDesignUserDocModel.prototype = new YjxBaseModel();

// 取得表名
YjxDesignUserDocModel.prototype.getTableName = function(){
    return 'yjx_design_user_doc';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxDesignUserDocModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'doc_id='+this.doc_id;
};


/**
 * 修改作品名
 *
 * @author 严旭东
 * @date 2017-11-17
 *
 * @param userId 用户唯一标识
 * @param docId 作品唯一标识
 * @param name 用户修改名
 * @param callback  回调
 *          err: 查询失败
 *          results : {}
 */
YjxDesignUserDocModel.prototype.updataDesignUserDocName = function(userId,docId,name,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxDesignUserDocModel.updataVideoUserDoc getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =' UPDATE yjx.yjx_design_user_doc ' +
                '  SET doc_name = "'+name +'" '  +
                '  WHERE user_id = ' + userId +
                '  AND uni_doc_id =  ' + docId;
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxDesignUserDocModel.updataVideoUserDoc Err: ' + error);
                return callback(error, null);
            }
            return callback(null, results)
        })
    })
};

/**
 * 获取作品的提纲微调信息
 * @author 王俊
 * @date 2017-11-18
 *
 * @param callback
 *          error：null 表示无错误
 *          data：结构如下：
 *               {
 *                 "bleedHeight": 36,
 *                 "bleedWidth": 36,
 *                 "coreStructure": {},            // 文档核心结构字符串
 *                 "designId": 738,
 *                 "designNm": "红色线型简约名片",
 *                 "pageCount": 2,
 *                 "pageHeight": 709,
 *                 "pageWidth": 1134,
 *                 "printPxW": 1200, // 印刷用像素值
 *                 "printPxH": 1900, // 印刷用像素值
 *                 "productId": 0,
 *                 "productNm": "",
 *                 "textObjects": “",               //  微调初始化字符串
 *                 "typeS": 40101                   // 三级分类
 *               }
 *
 * 注意:
 * 1. 复制自 mysql/mapping TgUserDocMode.prototype.getTgAndFineTuneInfoOfUserDoc
 * 2. 调用此方法的模型需存在以下属性
 *      doc_id: 用户设计作品表的唯一标识
 */
YjxDesignUserDocModel.prototype.getTgAndFineTuneInfoOfUserDoc  = function(callback){
    var THIS = this;
    pool.pool.getConnection(function(err, connection) {

        var sql  =
            '	 		SELECT d.data AS coreStructure,  '+
            '              		NULL AS designNm,  '+
            '              		( '+
            '              			SELECT COUNT(p.page_id) '+
            '              			FROM yjx.yjx_design_user_page p '+
            '              			WHERE p.`doc_id` =  '+ THIS.doc_id+
            '              			AND p.del_flg = 0 '+
            '              		) AS pageCount,  '+
            '              		d.design_id AS designId,  '+
            '              		d.doc_id AS productId,  '+
            '              		d.doc_name AS productNm,  '+
            '              		d.finetune_data AS textObjects,  '+
            '              		d.type_id AS typeS,  '+
            '              		s.width AS pageWidth,  '+
            '              		s.height AS pageHeight,  '+
            '              		ceil(s.width / s.ratio) AS printPxW,  '+
            '              		ceil(s.height / s.ratio) AS printPxH, '+
            '              		s.height AS pageHeight,  '+
            '              		ceil(s.dpi / 25.4 * s.`bleed`) AS bleedWidth, '+
            '              		ceil(s.dpi / 25.4 * s.`bleed`) AS bleedHeight '+
            '              FROM yjx.yjx_design_user_doc d,  '+
            // '              	itbour.tg_map_doc m,  '+
            '              	itbour.tg_size s '+
            '              WHERE d.`doc_id` = '+ THIS.doc_id+
            '              	AND d.del_flg = 0 '+
            '              	AND d.size_id = s.size_id '+
            // '              	AND d.map_id = m.map_id '+
            // '              	AND m.del_flg = 0 '+
            // '              	AND m.size_id = s.size_id '+
            '              	AND s.del_flg = 0';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            if(result && result.length>0){
                callback(error, result[0]);
            }else{
                callback(error, null);
            }

        });
    });
};



/*
 * 参数:callback: 回调
 * 参数 doc_id: 文档id
 * 参数 orderBy: 0或空:doc_id顺序, 1:create_time倒序
 * 参数 withoutPgInfo: 1不关联pg表
 * */
/**
 * 根据文档id获取文档基本信息
 *
 * @author 王俊
 * @date 2017-11-19
 *
 * @param callback 回调
 *          error: 获取信息时报
 *          data: 基础信息
 * 注意:
 * 1. 此接口复制自 TgUserDocModel.prototype.getDocInfoById 具体功能待测
 * 2. 调用此方法的模型需具备以下属性
 *      doc_id: 设计作品 id
 *      orderBy: 0或空:doc_id顺序, 1:create_time倒序
 *      withoutPgInfo: 1不关联pg表
 *
 */
YjxDesignUserDocModel.prototype.getDocInfoById = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT t.doc_id, t.tg_id, t.map_id, t.design_id, t.doc_name, t.hash_tag, t.purpose, t.track, t.thumb AS doc_thumb, ' +
            ' t.finetune_flg, t.finetune_data, t.data, t.user_id, ' +
            ' DATE_FORMAT(t.create_time, "%Y-%m-%d %T") as create_time, ' +
            ' DATE_FORMAT(pg.update_time, "%Y-%m-%d %T") as update_time, pg.thumb, pg2.thumb AS design_thumb, ' +
            ' s.width, s.height, t.type_id, p.type_name, p.parent AS typeM, p.top_parent AS typeL '+
            ' FROM yjx.yjx_design_user_doc t, yjx.yjx_design_user_page pg, itbour.tg_size s, itbour.tg_type p, itbour.tg_design_page pg2 ' +
            ' WHERE t.del_flg = 0 AND t.doc_id = ' +THIS.doc_id+
            ' AND pg.page_index = 0 AND pg.del_flg = 0 AND t.doc_id = pg.doc_id '+
            ' AND pg2.page_index = 0 AND pg2.del_flg = 0 AND t.design_id = pg2.design_id '+
            ' AND s.del_flg = 0 AND s.size_id = t.size_id ' +
            ' AND p.del_flg = 0 AND p.type_id = t.type_id ';

        if(THIS.withoutPgInfo==1) {
            sql = ' SELECT t.doc_id, t.tg_id, t.map_id, t.design_id, t.doc_name, t.hash_tag, t.purpose, t.track, t.thumb AS doc_thumb, ' +
                ' t.finetune_flg, t.finetune_data, t.data, t.user_id, ' +
                ' DATE_FORMAT(t.create_time, "%Y-%m-%d %T") as create_time, ' +
                ' DATE_FORMAT(t.update_time, "%Y-%m-%d %T") as update_time, pg2.thumb AS design_thumb, ' +
                ' s.width, s.height, t.type_id, p.type_name, p.parent AS typeM, p.top_parent AS typeL '+
                ' FROM yjx.yjx_design_user_doc t, itbour.tg_size s, itbour.tg_type p, itbour.tg_design_page pg2 ' +
                ' WHERE t.del_flg = 0 AND t.doc_id = ' +THIS.doc_id+
                ' AND pg2.page_index = 0 AND pg2.del_flg = 0 AND t.design_id = pg2.design_id '+
                ' AND s.del_flg = 0 AND s.size_id = t.size_id ' +
                ' AND p.del_flg = 0 AND p.type_id = t.type_id ';
        }

        //var sqlValue = [THIS.user_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            //console.log();

            callback(error, result);
        });
    });
};

/**
 * 获取视频背景视频坑的位置
 *
 * @author 王俊
 * @date 2017-11-21
 *
 * @param docId     视频背景作品 id
 * @param callback  回调
 *          err:
 *          data: {
 *              x : x 坐标
 *              y : y 坐标
 *              w : w 宽
 *              h : h 高
 *          }
 */

YjxDesignUserDocModel.prototype.getViewBgContentVideoFrame = function (docId, callback) {

    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            return callback(getConErr, null);
        }

        var sql =
            ' SELECT ydud.video_pos ' +
            ' FROM yjx.yjx_design_user_doc ydud, ' +
            '      itbour.tg_type tt ' +
            ' WHERE ydud.doc_id = ' + docId +
            '   AND ydud.del_flg=0 ' +
            '   AND tt.type_id=ydud.type_id '+
            '   AND tt.top_parent=1030 '+ // 视频背景
            '   AND tt.del_flg=0 ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                return callback(queryErr || '该背景不存在或已删除', null);
            }
            var bg = results[0];
            if(!bg.video_pos || bg.video_pos.length <=2) {
                return callback('该背景无视频位置', null);
            }
            var retData = JSON.parse(bg.video_pos);
            return callback(queryErr, retData);
        })
    })
};

/**
 * 获取用户设计作品
 *
 * @author 王俊
 * @date 2017-11-22
 *
 * @param userId    用户 id
 * @param docId     作品 id
 * @param callback  回调
 *          error: 查询失败
 *          result: {
 *              doc_id: 作品 id,
 *              thumbs: 所有页缩略图数组, 按 pageIndex 排序, 空数组标记尚未排版
 *              type: tg_type 的一级分类 0 标记默认, 说明数据异常
 *              pageCnt: 该作品当前的总页数  0 标记默认, 说明尚未排版
 *          }
 */
YjxDesignUserDocModel.prototype.getDesignUserDocDownloadUrls = function (userId, docId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if(getConErr) {
            return callback(getConErr, null);
        }

        var sql =
            ' SELECT ydud.doc_id, ' +
            '        ydup.thumb, ' +
            '        tt.top_parent AS type' +
            ' FROM yjx.yjx_design_user_doc ydud, ' +
            '      yjx.yjx_design_user_page ydup, ' +
            '      itbour.tg_type tt ' +
            ' WHERE ydud.doc_id = ' + docId +
            '   AND ydud.user_id = ' + userId +
            '   AND ydup.doc_id = ydud.doc_id ' +
            '   AND tt.type_id = ydud.type_id ' +
            '   AND ydud.del_flg=0 ' +
            '   AND ydup.del_flg=0 ' +
            ' ORDER BY ydup.page_index ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if(queryErr) {
                return callback(queryErr, null);
            }
            var retData = {
                doc_id : docId,
                thumbs : [],
                type : 0,
                pageCnt : results.length || 0
            };
            if(results && results.length > 0) {
                for(var i=0; i< results.length; i++) {
                    var p = results[i];
                    if(!retData.type) {
                        retData.type = p.type
                    }
                    if(p.thumb) {
                        retData.thumbs.push(p.thumb)
                    }
                }
            }
            return callback(queryErr, retData);
        });
    })
};

/**
 * 获取用户设计作品的尺寸信息
 *
 * @author 王俊
 * @date 2017-11-22
 *
 * @param callback 回调
 *          err: 获取信息失败
 *          data: 设计作品的行数据
 * 注意:
 * 1. 复制自 TgUserDocModel.prototype.findSizeInfo 具体功能待测
 * 2. 调用此方法的数据模型需具备以下属性
 *      doc_id:  用户作品唯一标识
 */
YjxDesignUserDocModel.prototype.findSizeInfo = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT s.* '+
            ' FROM yjx.yjx_design_user_doc t,  '+
            ' 	   itbour.tg_size s  '+
            ' WHERE t.del_flg=0  '+
            ' AND t.doc_id= '+ THIS.doc_id +
            ' AND s.del_flg=0  '+
            ' AND s.size_id=t.size_id  ';


        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();
            if(error || !result || result.length <=0) {
                return callback(error || '暂无尺寸信息', null);
            }

            return callback(error, result[0]);

        });
    });
};
module.exports = YjxDesignUserDocModel;